<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工时ID" prop="worklogId">
        <el-input
          v-model="queryParams.worklogId"
          placeholder="请输入工时ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批层级" prop="step">
        <el-select v-model="queryParams.step" placeholder="请选择审批层级" clearable style="width: 180px">
          <el-option label="第1级（主管）" value="1" />
          <el-option label="第2级（销售）" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="审批人" prop="approver">
        <el-input
          v-model="queryParams.approver"
          placeholder="请输入审批人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable style="width: 220px">
          <el-option
            v-for="dict in approval_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审批时间" prop="approveTime">
        <el-date-picker clearable
          v-model="queryParams.approveTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择审批时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审批备注" prop="approveRemark">
        <el-input
          v-model="queryParams.approveRemark"
          placeholder="请输入审批备注"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['erp:approval:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['erp:approval:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['erp:approval:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['erp:approval:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="approvalList" 
      @selection-change="handleSelectionChange"
      class="approval-table"
      stripe
      border
      :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="工时ID" align="center" prop="worklogId" width="120" show-overflow-tooltip>
        <template #default="scope">
          <div class="worklog-info">
            <el-icon class="worklog-icon"><Clock /></el-icon>
            <span>{{ scope.row.worklogId || '暂无' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="审批层级" align="center" prop="step" width="100">
        <template #default="scope">
          <el-tag type="info" effect="plain" size="small">
            第{{ scope.row.step || 0 }}级
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approver" width="120">
        <template #default="scope">
          <div class="user-info" v-if="scope.row.approver">
            <el-avatar :size="24" class="user-avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span class="user-name">{{ scope.row.approver }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="status" width="120">
        <template #default="scope">
          <dict-tag :options="approval_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="审批时间" align="center" prop="approveTime" width="120">
        <template #default="scope">
          <div class="date-info" v-if="scope.row.approveTime">
            <el-icon class="date-icon"><Calendar /></el-icon>
            <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="审批备注" align="left" prop="approveRemark" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <div class="remark-info" v-if="scope.row.approveRemark">
            <el-icon class="remark-icon"><Document /></el-icon>
            <span class="remark-text">{{ scope.row.approveRemark }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['erp:approval:edit']"
            class="action-btn"
          >
            修改
          </el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['erp:approval:remove']"
            class="action-btn"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工时审批流对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="approvalRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工时ID" prop="worklogId">
          <el-input v-model="form.worklogId" placeholder="请输入工时ID" />
        </el-form-item>
        <el-form-item label="审批层级" prop="step">
          <el-select v-model="form.step" placeholder="请选择审批层级" style="width: 100%">
            <el-option label="第1级（主管）" value="1" />
            <el-option label="第2级（销售）" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="审批人" prop="approver">
          <el-tree-select
            v-model="form.approver"
            :data="orgTreeData"
            :props="orgTreeProps"
            node-key="id"
            :render-after-expand="false"
            placeholder="请选择审批人"
            check-strictly
            filterable
            :filter-node-method="filterUserNode"
            style="width: 100%"
            @node-click="handleApproverSelect"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in approval_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批时间" prop="approveTime">
          <el-date-picker clearable
            v-model="form.approveTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择审批时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批备注" prop="approveRemark">
          <el-input v-model="form.approveRemark" placeholder="请输入审批备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Approval">
import { listApproval, getApproval, delApproval, addApproval, updateApproval } from "@/api/erp/approval"
import { getUserDeptTree } from "@/api/organizational"
import { Clock, User, Calendar, Document } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const { approval_status } = proxy.useDict('approval_status')

const approvalList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 组织架构相关
const orgTreeData = ref([])
const orgTreeProps = { children: 'children', label: 'label' }
const userIdToInfoMap = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    worklogId: null,
    step: null,
    approver: null,
    status: null,
    approveTime: null,
    approveRemark: null,
  },
  rules: {
    worklogId: [
      { required: true, message: "工时ID不能为空", trigger: "blur" }
    ],
    step: [
      { required: true, message: "审批层级不能为空", trigger: "blur" }
    ],
    approver: [
      { required: true, message: "审批人不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询工时审批流列表 */
function getList() {
  loading.value = true
  listApproval(queryParams.value).then(response => {
    approvalList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    worklogId: null,
    step: null,
    approver: null,
    status: null,
    approveTime: null,
    approveRemark: null,
    createTime: null
  }
  proxy.resetForm("approvalRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加工时审批流"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getApproval(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改工时审批流"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["approvalRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateApproval(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addApproval(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除工时审批流编号为"' + _ids + '"的数据项？').then(function() {
    return delApproval(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('erp/approval/export', {
    ...queryParams.value
  }, `approval_${new Date().getTime()}.xlsx`)
}

/** 适配部门树数据结构 */
function adaptDeptTree(data) {
  const buildUserMap = (depts, parentDeptInfo = null) => {
    depts.forEach(dept => {
      const currentDeptInfo = {
        deptId: dept.deptId,
        deptName: dept.deptName
      }
      
      // 构建用户ID到信息的映射
      if (dept.userList) {
        dept.userList.filter(user => user.nickName !== 'admin' && user.nickName !== 'ry').forEach(user => {
          userIdToInfoMap.value[user.ddUserId] = {
            userName: user.nickName,
            deptId: dept.deptId,
            deptName: dept.deptName
          }
        })
      }
      // 递归处理子部门
      if (dept.children) {
        buildUserMap(dept.children, currentDeptInfo)
      }
    })
  }
  
  // 构建映射
  buildUserMap(data)
  
  return data.map(dept => ({
    id: dept.deptId,
    label: dept.deptName,
    children: [
      // 部门下的员工，过滤admin和ry
      ...(dept.userList ? dept.userList.filter(user => user.nickName !== 'admin' && user.nickName !== 'ry').map(user => ({
        id: user.ddUserId,
        label: user.nickName,
        isUser: true,
        deptId: dept.deptId,
        deptName: dept.deptName
      })) : []),
      // 子部门
      ...(dept.children ? adaptDeptTree(dept.children) : [])
    ]
  }))
}

/** 树节点过滤方法 */
function filterUserNode(value, data) {
  if (!value) return true
  return data.label.includes(value)
}

/** 审批人选择处理 */
function handleApproverSelect(data) {
  if (data.isUser) {
    // 选择的是用户，保存用户名
    form.value.approver = data.label
  }
}

getList()

// 预加载组织架构数据
getUserDeptTree().then(res => {
  if (res.code === 200) {
    orgTreeData.value = adaptDeptTree(res.data)
  }
})
</script>

<style scoped>
/* 表格样式优化 */
.approval-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.approval-table :deep(.el-table__body-wrapper) {
  border-radius: 0 0 8px 8px;
}

.approval-table :deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

.approval-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.approval-table :deep(.el-table__row:hover) {
  background-color: #f8f9fa !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 工时信息样式 */
.worklog-info {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.worklog-icon {
  color: #409eff;
  font-size: 16px;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.user-avatar {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #b3d8ff;
}

.user-name {
  font-size: 13px;
  color: #303133;
  font-weight: 500;
}

/* 日期信息样式 */
.date-info {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
}

.date-icon {
  color: #67c23a;
  font-size: 14px;
}

/* 备注信息样式 */
.remark-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.remark-icon {
  color: #909399;
  font-size: 14px;
  flex-shrink: 0;
}

.remark-text {
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
}

/* 暂无文本样式 */
.text-muted {
  color: #c0c4cc;
  font-size: 12px;
  font-style: italic;
}

/* 操作按钮样式 */
.action-btn {
  margin: 0 2px;
  font-size: 12px;
  padding: 4px 8px;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 状态标签优化 */
.approval-table :deep(.el-tag) {
  border-radius: 12px;
  font-weight: 500;
}

/* 层级标签样式 */
.approval-table :deep(.el-tag--info) {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

/* 树选择组件样式优化 */
:deep(.el-tree-select .el-tree-select__popper) {
  max-height: 400px;
}

:deep(.el-tree-select .el-tree-node) {
  font-size: 14px;
}

:deep(.el-tree-select .el-tree-node__content) {
  height: 32px;
  line-height: 32px;
}

:deep(.el-tree-select .el-tree-node__label) {
  font-size: 13px;
}

/* 树节点样式 */
:deep(.el-tree-node[data-is-user="true"] .el-tree-node__content) {
  color: #409eff;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .approval-table :deep(.el-table__header-wrapper),
  .approval-table :deep(.el-table__body-wrapper) {
    font-size: 12px;
  }
  
  .user-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .worklog-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .remark-info {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
}
</style>
